import React, { useState, useEffect, useRef } from 'react';
import { GridContent } from '@ant-design/pro-layout';
import { Menu, Form, Button, Dropdown, message } from 'antd';
import styles from './style.less';
import { FormComponentProps } from 'antd/lib/form';
import { queryRule } from './service';
import { bdExec } from '@/helpers/RequestHelper';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { DownOutlined } from '@ant-design/icons';
import moment from 'moment';
import { FormValueType } from './components/ConfigForm';
import ConfigForm from './components/ConfigForm';
import { addRule, updateRule, removeRule } from './service';
import * as tsxHelper from '@/helpers/TsxHelper';
import PreviewForm from '@/components/PreviewForm';

const { Item } = Menu;
interface ConfigListProps extends FormComponentProps { }

const handleAdd = async (fields: FormValueType) => {
  return bdExec({ fn: addRule, args: fields, successMsg: '添加成功', failMsg: '添加失败请重试！' });
};

const handleUpdate = async (fields: FormValueType) => {
  return bdExec({ fn: updateRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};

const handleRemove = async (selectedRows: any[]) => {
  if (!selectedRows) return true;
  const ids: any = selectedRows.map(row => row.id).toString();
  return bdExec({ fn: removeRule, args: { ids }, successMsg: '删除成功，即将刷新', failMsg: '删除失败，请重试！', hasLoading: false });
};

const ConfigList: React.FC<ConfigListProps> = (props) => {

  let main: HTMLDivElement | undefined | any = undefined;
  const actionRef = useRef<ActionType>();
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [selectIndex, setSelectIndex] = useState<string>('');
  const [mode, setMode] = useState<any>('inline');
  const [rowKeys, setRowKeys] = useState<string[] | number[]>([]);
  const [isUpdate, setIsUpdate] = useState<boolean>(false);
  const [radioType, setRadioType] = useState<string | 'string' | 'switch' | 'date' | 'file' | 'color'>('string');
  const [picture, setPicture] = useState<any[]>([]);
  const [color, setColor] = useState<string>('#1890ff');
  const [stateData, setStateData] = useState<any>({ common: {} });
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  useEffect(() => {
    window.addEventListener('resize', resize);
    resize();
    initData();
    return () => window.removeEventListener('resize', resize);
  }, []);

  const columns: ProColumns<any>[] = [
    {
      title: '变量名',
      dataIndex: 'name',
    },
    {
      title: '变量标识',
      dataIndex: 'nickname',
      hideInSearch: true,
    },
    {
      title: '变量值',
      dataIndex: 'content',
      width: '30%',
      render: (value, record) => (record.type == 'file' ?
        <img src={record.content} width='130px' onClick={() => {
          setPreviewImg(record.content)
          handlePreviewModalVisible(true)
        }} /> : (record.type == "color"? <div style={{display: "flex"}}><p>{record.content}</p><p style={{width:30,height:20,backgroundColor:record.content,marginLeft:5 }}></p></div> :record.content)
      )
    },
    {
      title: '排序',
      dataIndex: 'rank_num',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      sorter: true,
      hideInSearch: true,
      render: (val: any) => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: React.SetStateAction<any>) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              initValuesData(record);
            }}
          >
            编辑
          </a>
        </>
      ),
    },
  ];

  const initData = (params?: any) => {
    const args: any = {};
    params && params.selectIndex != '' && (args.config_group_id = params.selectIndex);

    console.log('....1111')
    window.location.pathname.split('/').map((v:any) => {
      if(v.indexOf('type_') > -1){
        console.log('....')
        args.type = v.split('type_')[1]
      }
    })


    return bdExec({
      fn: queryRule,
      args,
      failMsg: '请求数据失败',
      hasCallBack: true,
      hasLoading: false,
    }).then((res: any) => {
      if (res.execStatus) {
        // todo 注意： 如果state为一个对象时，这个时候需要进行合并的。 
        setStateData(res.data)
        params && setSelectIndex(params.selectIndex == '' ?
          res.data.common.sideBarList[0].id.toString() : params.selectIndex);
        return res.data.listData;
      }
    })
  }

  const initValuesData = (record: any) => {
    setIsUpdate(true);
    setStepFormValues(record);
    setRadioType(record.type);
    record.type == 'color' && setColor(record.content);
    record.type == 'file' && buildPicture(record.content);
  }

  const getMenu = () => {
    const menuMap = stateData.common.sideBarList || [];
    return menuMap.map((item: any) => <Item key={`${item.id}`}>{item.name}</Item>);
  };

  const getRightTitle = () => {
    const menuMap = stateData.common.sideBarList || [];
    const selectItem = menuMap.filter((item: any) => item.id.toString() === selectIndex);
    return selectItem.length > 0 ? selectItem[0].name : '';
  };

  const selectKey = (key: string) => {
    setSelectIndex(key);
    // if (actionRef.current) {
    //   actionRef.current.reload();
    // }
  };

  const resize = () => {
    if (!main) {
      return;
    }
    requestAnimationFrame(() => {
      if (!main) {
        return;
      }
      let mode: 'inline' | 'horizontal' = 'inline';
      const { offsetWidth } = main;
      if (main.offsetWidth < 641 && offsetWidth > 400) {
        mode = 'horizontal';
      }
      if (window.innerWidth < 768 && offsetWidth > 400) {
        mode = 'horizontal';
      }
      setMode(mode);
    });
  };

  const handleChangeType = (value: any) => {
    console.log('type-->', value)
    setRadioType(value)
  }

  const handleSetPicture = (value: any) => {
    setPicture(value)
  }

  const handleSetColor = (value: any) => {
    setColor(value);
  }

  const buildPicture = (url: any) => {
    if (url) {
      setPicture([{
        uid: '-1',
        name: url.split('/').pop(),
        status: 'done',
        url: url,
        thumbUrl: url,
      }]);
    }
  }

  const handleOnSubmit = (value: FormValueType) => {
    return new Promise((resolve, reject) => {
      let s = isUpdate ? handleUpdate(value) : handleAdd(value);
      resolve(s);
    }).then(status => {
      if (status) {
        handleModalVisible(false);
        setPicture([]);
        setColor('#1890ff');
        if (actionRef.current) {
          actionRef.current.reload();
        }
      }
      return status; // 返回执行结果:boolean, 子组件接收此值来判断是否重置表单数据
    })
  }

  // console.log('update-->selectIndex-->', selectIndex)
  return (
    <GridContent>
      <div
        className={styles.main}
        ref={ref => {
          if (ref) {
            main = ref;
          }
        }}
      >
        <div className={styles.leftMenu}>
          <Menu
            mode={mode}
            selectedKeys={[selectIndex]}
            onClick={({ key }) => selectKey(key)}
          >
            {getMenu()}
          </Menu>
        </div>
        <div className={styles.right}>
          <ProTable<any>
            headerTitle={getRightTitle()}
            actionRef={actionRef}
            rowKey="key"
            search={false}
            pagination={{
              showSizeChanger: true,
            }}
            toolBarRender={(action, { selectedRows }) => [
              <Button icon={'plus'} type="primary"
                onClick={() => {
                  handleModalVisible(true)
                  setIsUpdate(false);
                }}
              >
                新建
              </Button>,
              selectedRows && selectedRows.length > 0 && (
                <Dropdown
                  overlay={
                    <Menu
                      onClick={async e => {
                        if (e.key === 'remove') {
                          tsxHelper.showDeleteConfirm(
                            'danger',
                            handleRemove,
                            selectedRows,
                            () => {
                              setRowKeys([]);
                              action.reload();
                            }
                          )
                        }
                      }}
                      selectedKeys={[]}
                    >
                      <Menu.Item key="remove">批量删除</Menu.Item>
                    </Menu>
                  }
                >
                  <Button>
                    批量操作 <DownOutlined />
                  </Button>
                </Dropdown>
              ),
            ]}
            tableAlertRender={(selectedRowKeys, selectedRows) => (
              <div>
                已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
              </div>
            )}
            request={(params) => initData(params)}
            // 这个参数会自动注入到params中去，如果selectIndex修改， 还会触发reload()
            params={{
              selectIndex,
            }}
            columns={columns}
            rowSelection={{
              onChange: (selectedRowKeys, selectedRows) => {
                setRowKeys(selectedRowKeys);
              },
              selectedRowKeys: rowKeys,
            }}
          />
          <ConfigForm
            onSubmit={(value) => handleOnSubmit(value)}
            onCancel={() => {
              handleModalVisible(false);
              setPicture([]);;
            }}
            modalVisible={createModalVisible}
            handleChangeType={handleChangeType}
            handleSetPicture={handleSetPicture}
            handleSetColor={handleSetColor}
            values={stepFormValues}
            otherValues={{
              common: stateData.common || {},
              selectIndex,
              isUpdate,
              radioType,
              picture,
              color
            }}
            changeParamType={() => { }}
          />
          {
            previewModelVisible && (
                <PreviewForm
                    previewModelVisible={previewModelVisible}
                    onVisibleModel={handlePreviewModalVisible}
                    previewImg={previewImg}
                />
            )
            }
        </div>
      </div>
    </GridContent>
  );
}

export default Form.create<ConfigListProps>()(ConfigList);

